// 解析URL参数
function getUrlParam(name) {
    const url = new URL(window.location.href);
    return url.searchParams.get(name);
}

//随机函数
function getRandom(min, max) {
    return Math.random() * (max - min) + min;
}

// 赛车类
class RacingCar {
  constructor(isPlayer = false, color = 'red', carNumber = 1) {
    this.isPlayer = isPlayer;
    this.color = color;
    this.carNumber = carNumber;
    this.hasFinished = false; // 新增完成状态标记
    this.finishTime = 0; // 新增完成时间记录
    this.tireInventory = {
      [TIRE_SOFT]: 2,
      [TIRE_MEDIUM]: 2,
      [TIRE_HARD]: 2
    };
    this.reset();
  }

  reset() {
    this.carAngle = 0;
    this.lapCount = 0;
    this.lastLapTime = 0;
    this.totalTime = 0;
    this.currentLapStartTime = 0;
    this.isNewLap = false;
    this.tireType = TIRE_SOFT;
    this.tireWear = 0;
    this.totalPitTime = 0; // 总停车时间
    this.currentPitTime = 0; // 当前停车时间
    // 从localStorage读取参数，提供默认值
    const playerSpeed = parseFloat(localStorage.getItem('playerSpeed')) || 0.001;
    const PIT_STOP_DURATION_MAX = parseInt(localStorage.getItem('pitStopDurationMax')) || 4000;
    
    // 设置赛车基础速度
    const baseSpeed = this.isPlayer ? playerSpeed : (parseFloat(localStorage.getItem('aiSpeeds')) || 0.0008);
    // const variation = baseSpeed * 0.1; // 10%变化
    const randomspeed = getRandom(baseSpeed * 0.9, baseSpeed * 1.1)
    this.targetBaseSpeed = randomspeed;
    this.currentBaseSpeed = this.targetBaseSpeed;
    this.isPitting = false;
    this.pitStartTime = 0;
    this.pitStopDuration = 0;
    this.pitTargetTire = TIRE_SOFT;
    this.isPitRequested = false;
  }

  update() {
    // 平滑速度过渡
    this.currentBaseSpeed += (this.targetBaseSpeed - this.currentBaseSpeed) * accelerationFactor;
    
    if (this.isPitting) {
      const now = performance.now();
      this.currentPitTime = (now - this.pitStartTime) / 1000;
      
              // 更新停车时间显示
              if (this.isPlayer) {
                document.getElementById('currentPitTime').textContent = this.currentPitTime.toFixed(1) + 's';
                document.getElementById('pitTimeDisplay').style.display = 'block';
              }
      
      if (now - this.pitStartTime >= this.pitStopDuration) {
        this.isPitting = false;
        this.totalPitTime += this.currentPitTime;
        this.tireType = this.pitTargetTire;
        this.tireWear = 0;
        this.targetBaseSpeed = 0.001 + (this.isPlayer ? Math.random() * 0.002 : 0.0015);
        
        // 隐藏停车时间显示
        if (this.isPlayer) {
          document.getElementById('pitTimeDisplay').style.display = 'none';
        }
      }
      return;
    }

    // AI控制逻辑
    if (!this.isPlayer) {
      // 简单AI: 随机决定是否进站
      if (this.tireWear > 70 && Math.random() < 0.01) {
        this.isPitRequested = true;
        // 只选择有库存的轮胎
        const availableTires = [];
        if (this.tireInventory[TIRE_SOFT] > 0) availableTires.push(TIRE_SOFT);
        if (this.tireInventory[TIRE_MEDIUM] > 0) availableTires.push(TIRE_MEDIUM);
        if (this.tireInventory[TIRE_HARD] > 0) availableTires.push(TIRE_HARD);
        
        if (availableTires.length > 0) {
          this.pitTargetTire = availableTires[Math.floor(Math.random() * availableTires.length)];
          this.tireInventory[this.pitTargetTire]--;
        } else {
          this.isPitRequested = false; // 没有可用轮胎
        }
      }
    }

    // 进站逻辑
    if (this.isPitRequested && this.carAngle >= PIT_AREA_START && this.carAngle <= PIT_AREA_END) {
      this.isPitting = true;
      this.isPitRequested = false;
      this.pitStartTime = performance.now();
                  this.pitStopDuration = this.isPlayer 
                    ? getRandom(PIT_STOP_DURATION_MIN, PIT_STOP_DURATION_MAX)
                    : getRandom(AI_PIT_STOP_DURATION_MIN, AI_PIT_STOP_DURATION_MAX);
      this.targetBaseSpeed = 0;
      return;
    }

    // 速度计算
    let speedMultiplier = 1;
    switch(this.tireType) {
      case TIRE_SOFT: speedMultiplier = 0.96; break;
      case TIRE_MEDIUM: speedMultiplier = 0.92; break;
      case TIRE_HARD: speedMultiplier = 0.90; break;
    }
    
    if (this.tireWear >= 50) {
      speedMultiplier *= (1 - (this.tireWear - 50) * 0.005);
    }
    
    const prevAngle = this.carAngle;
    this.carAngle += this.currentBaseSpeed * speedMultiplier;
    
    // 确保carAngle在0-1范围内
    if (this.carAngle > 1) {
        this.carAngle -= 1;
    }
    
    // 新圈检测 - 更精确的检测逻辑
    const now = performance.now();
    const isOnFinishStraight = (prevAngle % 1) < 0.5 && (this.carAngle % 1) >= 0.5;
    
    if (isOnFinishStraight && !this.isNewLap) {
      this.isNewLap = true;
      if (this.currentLapStartTime > 0) {
        this.lastLapTime = now - this.currentLapStartTime;
        this.totalTime += this.lastLapTime;
      }
      this.currentLapStartTime = now;
      this.lapCount++;
      
      // 检查赛车是否完成比赛
      if (this.lapCount >= totalLaps && !this.hasFinished) {
        this.hasFinished = true;
        const now = performance.now();
        this.finishTime = this.totalTime + (this.currentLapStartTime > 0 ? now - this.currentLapStartTime : 0);
        // 停止该赛车的更新
        this.targetBaseSpeed = 0;
        this.currentBaseSpeed = 0;
        
        // 检查所有赛车是否完成
        checkRaceFinish();
      }
      
      // 轮胎损耗
      switch(this.tireType) {
        case TIRE_SOFT: this.tireWear += 4; break;
        case TIRE_MEDIUM: this.tireWear += 3; break;
        case TIRE_HARD: this.tireWear += 2; break;
      }
      this.tireWear = Math.min(this.tireWear, 100);
      
      // 设置新速度 - 每圈重新随机速度
      if (this.isPlayer) {
          // 玩家赛车速度在playerSpeed基础上±15%随机
          const baseSpeed = parseFloat(localStorage.getItem('playerSpeed')) || 0.001;
          // const variation = baseSpeed * 0.15; // 15%变化
          const randomSpeed = getRandom(baseSpeed * 0.85, baseSpeed * 1.15)
          this.targetBaseSpeed = randomSpeed;
      } else {
          // 从localStorage读取预设AI速度并做±15%随机
          const aiSpeeds = localStorage.getItem('aiSpeeds') || 0.0008;
          // const aiIndex = this.carNumber - 2; // AI赛车编号从2开始
          // const baseSpeed = parseFloat(aiSpeeds[aiIndex]) || 0.003;
          // const variation = baseSpeed * 0.15; // 15%变化
          const randomSpeed = getRandom(aiSpeeds * 0.85, aiSpeeds * 1.15)
          this.targetBaseSpeed = randomSpeed;
      }
    } else if (!isOnFinishStraight) {
      this.isNewLap = false;
    }
  }

  draw(ctx) {
    const distance = this.carAngle * trackLength;
    let x, y;
    let isOnFinishStraight = false;

    // 位置计算 (与原来相同)
    if (distance < trackWidth - 2 * cornerRadius) {
      x = trackCenterX - trackWidth / 2 + cornerRadius + distance;
      y = trackCenterY - trackHeight / 2;
    } else if (distance < trackWidth - 2 * cornerRadius + Math.PI * cornerRadius) {
      const arcDistance = distance - (trackWidth - 2 * cornerRadius);
      const arcAngle = arcDistance / cornerRadius - Math.PI / 2;
      x = trackCenterX + trackWidth / 2 - cornerRadius + cornerRadius * Math.cos(arcAngle);
      y = trackCenterY + cornerRadius * Math.sin(arcAngle);
    } else if (distance < 2 * (trackWidth - 2 * cornerRadius) + Math.PI * cornerRadius) {
      const straightDistance = distance - (trackWidth - 2 * cornerRadius + Math.PI * cornerRadius);
      x = trackCenterX + trackWidth / 2 - cornerRadius - straightDistance;
      y = trackCenterY + trackHeight / 2;
      isOnFinishStraight = true;
    } else {
      const arcDistance = distance - (2 * (trackWidth - 2 * cornerRadius) + Math.PI * cornerRadius);
      const arcAngle = arcDistance / cornerRadius + Math.PI / 2;
      x = trackCenterX - trackWidth / 2 + cornerRadius + cornerRadius * Math.cos(arcAngle);
      y = trackCenterY + cornerRadius * Math.sin(arcAngle);
    }

    // 绘制赛车
    ctx.beginPath();
    ctx.arc(x, y, 5, 0, 2 * Math.PI);
    ctx.fillStyle = this.color;
    ctx.fill();
    
    // 绘制车号
    ctx.fillStyle = 'white';
    ctx.font = '10px Arial';
    ctx.textAlign = 'center';
    ctx.fillText(this.carNumber.toString(), x, y + 3);
  }
}

// 全局变量
let canvas;
let ctx;
const trackCenterX = 400;
const trackCenterY = 200;
let totalLaps = Math.floor(Math.random() * 11) + 45; // 45-55随机圈数
let isRaceFinished = false;

// 轮胎类型常量
const TIRE_SOFT = 0;
const TIRE_MEDIUM = 1;
const TIRE_HARD = 2;

// 赛道参数
const trackWidth = 640;
const trackHeight = 240;
const cornerRadius = trackHeight / 2;
const trackLength = 2 * (trackWidth - 2 * cornerRadius) + 2 * Math.PI * cornerRadius;
const accelerationFactor = 0.002;
const PIT_AREA_START = 0.25;
const PIT_AREA_END = 0.35;
const PIT_STOP_DURATION_MIN = 2500; // 玩家最小停车时间(ms)
const PIT_STOP_DURATION_MAX = 4000; // 玩家最大停车时间(ms)
const AI_PIT_STOP_DURATION_MIN = 2700; // AI最小停车时间(ms) 
const AI_PIT_STOP_DURATION_MAX = 4000; // AI最大停车时间(ms)

// 赛车数组
const cars = [];
const playerCar = new RacingCar(true, 'red', 1);
cars.push(playerCar);

// 添加AI赛车
const carColors = ['blue', 'green', 'yellow', 'orange', 'purple'];
for (let i = 0; i < 5; i++) {
  cars.push(new RacingCar(false, carColors[i], i + 2));
}



// 绘制操场状赛道
function drawTrack() {
  ctx.beginPath();
  ctx.moveTo(trackCenterX - trackWidth / 2 + cornerRadius, trackCenterY - trackHeight / 2);
  ctx.lineTo(trackCenterX + trackWidth / 2 - cornerRadius, trackCenterY - trackHeight / 2);
  ctx.arc(trackCenterX + trackWidth / 2 - cornerRadius, trackCenterY, cornerRadius, -Math.PI / 2, Math.PI / 2);
  ctx.lineTo(trackCenterX - trackWidth / 2 + cornerRadius, trackCenterY + trackHeight / 2);
  ctx.arc(trackCenterX - trackWidth / 2 + cornerRadius, trackCenterY, cornerRadius, Math.PI / 2, -Math.PI / 2);
  ctx.closePath();
  ctx.fillStyle = 'gray';
  ctx.fill();

  // 绘制进站区标识
  const pitStartX = trackCenterX - trackWidth / 2 + cornerRadius + 
                   (trackWidth - 2 * cornerRadius) * PIT_AREA_START;
  const pitEndX = trackCenterX - trackWidth / 2 + cornerRadius + 
                 (trackWidth - 2 * cornerRadius) * PIT_AREA_END;
  
  ctx.beginPath();
  ctx.moveTo(pitStartX, trackCenterY - trackHeight / 2 - 10);
  ctx.lineTo(pitEndX, trackCenterY - trackHeight / 2 - 10);
  ctx.strokeStyle = 'red';
  ctx.lineWidth = 3;
  ctx.stroke();

  ctx.font = '14px Arial';
  ctx.fillStyle = 'red';
  ctx.textAlign = 'center';
  ctx.fillText('PIT LANE', (pitStartX + pitEndX) / 2, trackCenterY - trackHeight / 2 - 20);
}

// 格式化时间为MM:SS.mmm
function formatTime(ms) {
  const minutes = Math.floor(ms / 60000);
  const seconds = Math.floor((ms % 60000) / 1000);
  const milliseconds = Math.floor(ms % 1000);
  return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}.${milliseconds.toString().padStart(3, '0')}`;
}

// 主循环
function animate() {
  // 清除画布
  ctx.clearRect(0, 0, canvas.width, canvas.height);

  // 绘制赛道
  drawTrack();

  if (!isRaceFinished) {
    // 更新并绘制所有赛车
    cars.forEach(car => {
      car.update();
      car.draw(ctx);
    });

    // 计算并显示排名
    updateRankings();

    // 绘制玩家赛车信息
    drawPlayerInfo();

    // 循环动画
    requestAnimationFrame(animate);
  } else {
    // 比赛结束，只绘制赛车当前位置
    cars.forEach(car => {
      car.draw(ctx);
    });
    
    // 禁用进站按钮
    document.getElementById('pitButton').disabled = true;
  }
}

// 检查比赛是否结束
function checkRaceFinish() {
  // 检查所有赛车是否都完成了比赛
  const allFinished = cars.every(car => car.hasFinished);
  if (allFinished) {
    isRaceFinished = true;
    // 按完成时间排序
    const sortedCars = [...cars].sort((a, b) => a.finishTime - b.finishTime);
    
    // 显示比赛结束信息
    document.getElementById('raceInfo').innerHTML += `
      <div id="raceResult" style="margin-top: 20px; background: #333; color: white; padding: 10px; border-radius: 5px;">
        <h3>比赛结束 - 总圈数: ${totalLaps}</h3>
        <table id="finalTable" style="width: 100%;">
          <thead>
            <tr>
              <th>名次</th>
              <th>车号</th>
              <th>总用时</th>
            </tr>
          </thead>
          <tbody id="finalTableBody"></tbody>
        </table>
      </div>
    `;
    
    // 填充最终成绩表
    const finalTableBody = document.getElementById('finalTableBody');
    sortedCars.forEach((car, index) => {
      const row = document.createElement('tr');
      row.innerHTML = `
        <td>${index + 1}</td>
        <td style="color:${car.color}">${car.carNumber}</td>
        <td>${formatTime(car.finishTime)}</td>
      `;
      finalTableBody.appendChild(row);
      
      // 如果是玩家赛车且完成比赛，计算奖励
      if (car.isPlayer && car.hasFinished) {
        try {
          const currentMoney = parseInt(localStorage.getItem('playerMoney')) || 100000;
          const rewards = [10000000, 8000000, 5000000, 3500000, 2500000, 1500000];
          const reward = index < rewards.length ? rewards[index] : 0;
          const newMoney = currentMoney + reward;
          localStorage.setItem('playerMoney', newMoney.toString());
          
          // 显示奖励信息
          document.getElementById('raceResult').innerHTML += `
            <div style="margin-top: 10px; color: gold; font-weight: bold;">
              获得奖励: ￥${reward.toLocaleString()}
            </div>
          `;
        } catch (e) {
          console.error('更新奖励失败:', e);
        }
      }
    });
  }
}

// 更新赛车排名
function updateRankings() {
  // 按圈数和位置排序
  cars.sort((a, b) => {
    if (a.lapCount !== b.lapCount) return b.lapCount - a.lapCount;
    return b.carAngle - a.carAngle;
  });
}

// 绘制玩家赛车信息
function drawPlayerInfo() {
  const now = performance.now();
  const currentLapTime = playerCar.currentLapStartTime > 0 ? 
    now - playerCar.currentLapStartTime : 0;
  
  ctx.font = '16px monospace';
  ctx.fillStyle = 'black';
  ctx.textAlign = 'left';
  
  // 绘制起终点线
  ctx.beginPath();
  ctx.moveTo(trackCenterX - 20, trackCenterY + trackHeight / 2);
  ctx.lineTo(trackCenterX + 20, trackCenterY + trackHeight / 2);
  ctx.strokeStyle = 'white';
  ctx.lineWidth = 2;
  ctx.stroke();
  
  // 轮胎类型名称
  const tireNames = ['Soft', 'Medium', 'Hard'];
  
  // 绘制计时信息
  ctx.fillText(`Lap: ${formatTime(currentLapTime)}`, 20, canvas.height - 60);
  ctx.fillText(`Last: ${playerCar.lastLapTime > 0 ? 
    formatTime(playerCar.lastLapTime) : '--:--.---'}`, 20, canvas.height - 40);
  ctx.fillText(`Total: ${formatTime(playerCar.totalTime + currentLapTime)}`, 
    200, canvas.height - 40);
  
  // 绘制轮胎状态
  ctx.fillText(`Tire: ${tireNames[playerCar.tireType]}`, 20, canvas.height - 20);
  
  // 轮胎损耗百分比
  if (playerCar.tireWear >= 50) {
    ctx.fillStyle = 'red';
  }
  ctx.fillText(`Wear: ${playerCar.tireWear}%`, 200, canvas.height - 20);
  ctx.fillStyle = 'black';

  // 显示排名
  const playerRank = cars.findIndex(car => car.isPlayer) + 1;
  ctx.fillText(`Position: ${playerRank}/${cars.length}`, 
    canvas.width - 150, canvas.height - 20);

  // 显示进站状态和总停车时间
  if (playerCar.isPitting) {
    ctx.fillStyle = 'blue';
    ctx.fillText(`Pitting... ${((playerCar.pitStopDuration - 
      (now - playerCar.pitStartTime)) / 1000).toFixed(1)}s`, 
      canvas.width - 200, canvas.height - 40);
    ctx.fillStyle = 'black';
  } else if (playerCar.isPitRequested) {
    ctx.fillStyle = 'blue';
    ctx.fillText(`Pit requested`, canvas.width - 200, canvas.height - 40);
    ctx.fillStyle = 'black';
  }
  
  // 显示停车时间
  ctx.fillText(`Pit Time: ${playerCar.currentPitTime.toFixed(1)}s`, 
    canvas.width - 200, canvas.height - 60);
}

// 初始化
function init() {
  canvas = document.getElementById('raceTrack');
  ctx = canvas.getContext('2d');
  // 初始化显示总圈数
  document.getElementById('totalLapsDisplay').textContent = totalLaps;
  animate();
}

// 添加禁用按钮样式
const style = document.createElement('style');
style.textContent = `
  .choseTireButton.disabled {
    opacity: 0.5;
    cursor: not-allowed;
    background-color: #ccc !important;
  }
  .choseTireButton.disabled:hover {
    background-color: #ccc !important;
  }
`;
document.head.appendChild(style);

// 初始化进站按钮和面板
function initPitUI() {
    const pitButton = document.getElementById('pitButton');
    const pitPanel = document.getElementById('pitPanel');
    const softTire = document.getElementById('softTire');
    const mediumTire = document.getElementById('mediumTire');
    const hardTire = document.getElementById('hardTire');

    // 更新轮胎按钮状态
    function updateTireButtons() {
        // 更新按钮文本显示剩余数量
        softTire.textContent = `软胎 (${playerCar.tireInventory[TIRE_SOFT]})`;
        mediumTire.textContent = `中性胎 (${playerCar.tireInventory[TIRE_MEDIUM]})`;
        hardTire.textContent = `硬胎 (${playerCar.tireInventory[TIRE_HARD]})`;

        // 禁用库存为0的轮胎按钮
        softTire.disabled = playerCar.tireInventory[TIRE_SOFT] <= 0;
        mediumTire.disabled = playerCar.tireInventory[TIRE_MEDIUM] <= 0;
        hardTire.disabled = playerCar.tireInventory[TIRE_HARD] <= 0;

        // 添加禁用样式
        if (softTire.disabled) softTire.classList.add('disabled');
        else softTire.classList.remove('disabled');
        if (mediumTire.disabled) mediumTire.classList.add('disabled');
        else mediumTire.classList.remove('disabled');
        if (hardTire.disabled) hardTire.classList.add('disabled');
        else hardTire.classList.remove('disabled');
    }

    pitButton.addEventListener('click', () => {
        updateTireButtons();
        pitPanel.style.display = 'block';
    });

    softTire.addEventListener('click', () => {
        if (playerCar.tireInventory[TIRE_SOFT] > 0) {
            playerCar.pitTargetTire = TIRE_SOFT;
            playerCar.isPitRequested = true;
            playerCar.tireInventory[TIRE_SOFT]--;
            pitPanel.style.display = 'none';
        }
    });

    mediumTire.addEventListener('click', () => {
        if (playerCar.tireInventory[TIRE_MEDIUM] > 0) {
            playerCar.pitTargetTire = TIRE_MEDIUM;
            playerCar.isPitRequested = true;
            playerCar.tireInventory[TIRE_MEDIUM]--;
            pitPanel.style.display = 'none';
        }
    });

    hardTire.addEventListener('click', () => {
        if (playerCar.tireInventory[TIRE_HARD] > 0) {
            playerCar.pitTargetTire = TIRE_HARD;
            playerCar.isPitRequested = true;
            playerCar.tireInventory[TIRE_HARD]--;
            pitPanel.style.display = 'none';
        }
    });

    PitBack.addEventListener('click', () => {
        pitPanel.style.display = 'none';
    });
}

// 更新赛车位置
function updateCar() {
    // 平滑过渡到目标速度
    currentBaseSpeed += (targetBaseSpeed - currentBaseSpeed) * accelerationFactor;
    
    // 如果正在进站
    if (isPitting) {
        const now = performance.now();
        if (now - pitStartTime >= pitStopDuration) {
            // 进站完成
            isPitting = false;
            tireType = pitTargetTire;
            tireWear = 0;
            // 设置新的随机目标速度
            targetBaseSpeed = 0.001 + Math.random() * 0.002;
        }
        return; // 进站期间不更新位置
    }

    // 检查是否需要进站且处于进站区
    if (isPitRequested && carAngle >= PIT_AREA_START && carAngle <= PIT_AREA_END) {
        isPitting = true;
        isPitRequested = false;
        pitStartTime = performance.now();
        pitStopDuration = getRandom(PIT_STOP_DURATION_MIN, PIT_STOP_DURATION_MAX);
        // 进站前减速到0
        targetBaseSpeed = 0;
        return;
    }

    // 根据轮胎类型计算速度系数
    let speedMultiplier = 1;
    switch(tireType) {
        case TIRE_SOFT: speedMultiplier = 0.95; break;
        case TIRE_MEDIUM: speedMultiplier = 0.85; break;
        case TIRE_HARD: speedMultiplier = 0.73; break;
    }
    
    // 应用轮胎损耗导致的减速
    if (tireWear >= 50) {
        const wearPenalty = (tireWear - 50) * 0.005;
        speedMultiplier *= (1 - wearPenalty);
    }
    
    carSpeed = currentBaseSpeed * speedMultiplier;
    carAngle += carSpeed;
    if (carAngle > 1) {
        carAngle = 0; // 循环赛道
        // 每圈增加轮胎损耗
        switch(tireType) {
            case TIRE_SOFT: tireWear += 5; break;
            case TIRE_MEDIUM: tireWear += 3; break;
            case TIRE_HARD: tireWear += 2; break;
        }
        tireWear = Math.min(tireWear, 100); // 确保不超过100%
        // 每圈随机设置新的目标速度 (0.001-0.003)
        targetBaseSpeed = 0.001 + Math.random() * 0.002;
    }
}

// 绘制计时信息
function drawTimer() {
    const now = performance.now();
    const currentLapTime = currentLapStartTime > 0 ? now - currentLapStartTime : 0;
    
    ctx.font = '16px monospace';
    ctx.fillStyle = 'black';
    ctx.textAlign = 'left';
    
    // 绘制起终点线
    ctx.beginPath();
    ctx.moveTo(trackCenterX - 20, trackCenterY + trackHeight / 2);
    ctx.lineTo(trackCenterX + 20, trackCenterY + trackHeight / 2);
    ctx.strokeStyle = 'white';
    ctx.lineWidth = 2;
    ctx.stroke();
    
    // 轮胎类型名称
    const tireNames = ['Soft', 'Medium', 'Hard'];
    
    // 绘制计时信息
    ctx.fillText(`Lap: ${formatTime(currentLapTime)}`, 20, canvas.height - 60);
    ctx.fillText(`Last: ${lastLapTime > 0 ? formatTime(lastLapTime) : '--:--.---'}`, 20, canvas.height - 40);
    ctx.fillText(`Total: ${formatTime(totalTime + currentLapTime)}`, 200, canvas.height - 40);
    
    // 绘制轮胎状态
    ctx.fillText(`Tire: ${tireNames[tireType]}`, 20, canvas.height - 20);
    
    // 轮胎损耗百分比（损耗≥50%时显示红色）
    if (tireWear >= 50) {
        ctx.fillStyle = 'red';
    }
    ctx.fillText(`Wear: ${tireWear}%`, 200, canvas.height - 20);
    ctx.fillStyle = 'black'; // 恢复默认颜色

    // 显示进站状态
    if (isPitting) {
        ctx.fillStyle = 'blue';
        ctx.fillText(`Pitting... ${((pitStopDuration - (now - pitStartTime)) / 1000).toFixed(1)}s`, 
                     canvas.width - 200, canvas.height - 20);
        ctx.fillStyle = 'black';
    } else if (isPitRequested) {
        ctx.fillStyle = 'blue';
        ctx.fillText(`Pit requested`, canvas.width - 200, canvas.height - 20);
        ctx.fillStyle = 'black';
    }
}

// 排序状态
let currentSortMode = 'position'; // 'position' 或 'lapTime'

// 更新赛车信息表格
function updateRaceTable() {
    const tableBody = document.getElementById('raceTableBody');
    tableBody.innerHTML = '';
    
    // 获取最快圈速作为基准
    let fastestLap = Infinity;
    cars.forEach(car => {
        if (car.lastLapTime > 0 && car.lastLapTime < fastestLap) {
            fastestLap = car.lastLapTime;
        }
    });
    
    // 轮胎类型名称
    const tireNames = ['Soft', 'Medium', 'Hard'];
    
    // 按当前排序模式排序
    const sortedCars = [...cars].sort((a, b) => {
        if (currentSortMode === 'position') {
            // 按场上位置排序
            if (a.lapCount !== b.lapCount) return b.lapCount - a.lapCount;
            return b.carAngle - a.carAngle;
        } else {
            // 按单圈速度排序
            if (a.lastLapTime === 0 && b.lastLapTime === 0) return 0;
            if (a.lastLapTime === 0) return 1;
            if (b.lastLapTime === 0) return -1;
            return a.lastLapTime - b.lastLapTime;
        }
    });
    
    sortedCars.forEach((car, index) => {
        const row = document.createElement('tr');
        if (car.isPlayer) {
            row.classList.add('player-row');
        }
        
        // 计算时间差
        let timeDiff = '';
        if (car.lastLapTime > 0 && fastestLap < Infinity) {
            const diff = car.lastLapTime - fastestLap;
            if (diff > 0) {
                timeDiff = `(+${formatTime(diff)})`;
            }
        }
        
        row.innerHTML = `
            <td style="color:${car.color}">${car.carNumber}</td>
            <td>${index + 1}</td>
            <td>${car.lapCount}</td>
            <td>${car.lastLapTime > 0 ? formatTime(car.lastLapTime) : '--:--.---'} 
                <span class="time-diff">${timeDiff}</span>
            </td>
            <td>${tireNames[car.tireType]}</td>
            <td>${car.tireWear}%</td>
        `;
        
        tableBody.appendChild(row);
    });
}

// 切换排序方式
function initSortControls() {
    const sortByPosition = document.getElementById('sortByPosition');
    const sortByLapTime = document.getElementById('sortByLapTime');
    
    sortByPosition.addEventListener('click', () => {
        currentSortMode = 'position';
        sortByPosition.classList.add('active');
        sortByLapTime.classList.remove('active');
        updateRaceTable();
    });
    
    sortByLapTime.addEventListener('click', () => {
        currentSortMode = 'lapTime';
        sortByLapTime.classList.add('active');
        sortByPosition.classList.remove('active');
        updateRaceTable();
    });
}

// 页面加载完成后初始化
window.addEventListener('load', () => {
    init();
    initPitUI();
    initSortControls();
    
    // 初始化表格
    updateRaceTable();
    
    // 修改animate函数以更新表格
    const originalAnimate = animate;
    animate = function() {
        originalAnimate();
        updateRaceTable();
    };
});

function backToMenu() {
  window.location.href = "./F1车队模拟.html";
}